package ua.lk.phonebook;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ua.lk.phonebook.dao.UserDao;

/**
 * Servlet implementation class Users
 */
@WebServlet(description = "User's manager controller", urlPatterns = { "/users" })
public class Users extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static String LIST = "/userslist.jsp";
	private static String EDIT = "/useredit.jsp";
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Users() {
        super();
        // TODO Auto-generated constructor stub
    }
    
    

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		super.destroy();
	}



	/**
	 * @see Servlet#init(ServletConfig)
	 */
	public void init(ServletConfig config) throws ServletException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String action = request.getParameter("action");
		String forward = "";
		String userID = request.getParameter("userid");
		String filter = request.getParameter("filter");
		if( !response.isCommitted())
		{
			UserDao dao = new UserDao();

			switch(action.toUpperCase())
			{
			case "LIST":
				filter = (filter != null) ? (" where username like '%"+filter+"%' or login like '%"+filter+"%'") : "";
				request.setAttribute("users", dao.getUsers(filter));
				forward = LIST;
				break;
			case "EDIT":
				request.setAttribute("user", dao.getUserByID(userID));
				forward = EDIT;
				break;
			}
			dao.closeConnection();

			RequestDispatcher view = request.getRequestDispatcher(forward);
			//System.out.println("users_forward:"+forward);
			view.forward(request, response);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
